#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/7/5
# @Author  : LiJun
# @Email   : lijun@tianyancha.com
# @Version : 1.0.0

import os
import yaml
from appium import webdriver

from conf import config as cf
from common.appium_base_method import BasePage
from appium_0704.page.main_page import MainPage
from utils.read_yaml import read_yaml
from utils.get_device import get_devices_list
from utils.start_server import Server_fun

device_list = get_devices_list()

class App(BasePage):

    def start(self):
        if self.driver == None:
            # 启动应用
            self.log("driver == None 创建driver")
            port = 7007
            systemPort = 7008
            chromedriverPort = 7208
            udid = device_list.pop()

            # 开启appium服务
            Server_fun().start_server(port=port, bport=34000, chrome_port=chromedriverPort, device=udid)

            caps = read_yaml(f"{cf.CONFIG_DIR}/caps.yaml")["caps"]
            caps['udid'] = udid
            caps["systemPort"] = systemPort
            caps["chromedriverPort"] = chromedriverPort
            self.driver = webdriver.Remote(f"http://127.0.0.1:{port}/wd/hub", caps)
        else:
            self.log("复用driver")
            self.driver.launch_app()

        # with open(f"{cf.ELEMENT_DIR}/element.yaml", "r", encoding="utf-8") as f:
        #     self.element = yaml.safe_load(f)

        return self

    def restart(self):
        self.driver.close()
        self.driver.launch_app()

    def quit(self):
        self.driver.quit()

    def goto_main(self):
        # 进入主页 入口
        return MainPage(self.driver, element=self.element)
